package com.yy.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yy.mapper.ArticleMapper;
import com.yy.mapper.CollectionMapper;
import com.yy.pojo.Article;
import com.yy.pojo.Collection;
import com.yy.pojo.PageBean;
import com.yy.pojo.vo.ArticleVo;
import com.yy.service.ArticleService;
import com.yy.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private CollectionMapper collectionMapper;
    //新增文章
    @Override
    public void add(Article article) {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        article.setCreateUser(id);
        articleMapper.add(article);
    }

    @Override
    public void update(Article article) {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        article.setCreateUser(id);
        articleMapper.update(article);

    }

    @Override
    public PageBean<ArticleVo> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        //创建PageBean对象
        PageBean<ArticleVo> pb = new PageBean<>();
        //开启分页查询
        PageHelper.startPage(pageNum, pageSize);
        //调用mapper
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        List<ArticleVo> as=articleMapper.list(userId,categoryId,state);
        Page<ArticleVo> p =(Page<ArticleVo>) as;
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }

    @Override
    public void deleteArticle(Integer id) {
        articleMapper.deleteArticle(id);
    }

    //查询所有文章
    @Override
    public List<ArticleVo> listAll(Integer categoryId, String state,String title) {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        List<ArticleVo> articleVos = articleMapper.listAll(categoryId, state, title);
        articleVos.forEach(item->{
            Collection collection = collectionMapper.selectByUserIdAndArticleId(userId, item.getId());
            if (collection!=null){
                item.setIsCollection("1");
            }else{
                item.setIsCollection("0");
            }
        });
        return articleVos;
    }
}
